package com.liusy.serachengine.mail;



import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import org.apache.log4j.Logger;
import com.pff.PSTAttachment;
import com.pff.PSTException;
import com.pff.PSTFile;
import com.pff.PSTFolder;
import com.pff.PSTMessage;

public class ResolvePst {
	  int depth = -1; 
	  private List<PSTMessage> listEmail=new ArrayList<PSTMessage>();
	  private String       saveAttachPath = ""; 
	  private static Logger log            = Logger.getLogger(ResolvePst.class);
	  
	 public String getSaveAttachPath() {
		return saveAttachPath;
	}

	public void setSaveAttachPath(String saveAttachPath) {
		this.saveAttachPath = saveAttachPath;
	}
	

	
	public List<PSTMessage> getListEmail() {
		return listEmail;
	}

	public void processFolder(PSTFolder folder) throws PSTException, java.io.IOException {
		 depth++;                
		 // the root folder doesn't have a display name                 
		 if (depth > 0) {                         
			 printDepth();                         
			 System.out.println(folder.getDisplayName());
		 }                 
		 // go through the folders...                 
		 if (folder.hasSubfolders()) {        
			 Vector<PSTFolder> childFolders = folder.getSubFolders();   
			 for (PSTFolder childFolder : childFolders) {    
				 processFolder(childFolder);                     
			 }                
		 }                 
		 // and now the emails for this folder                
		 if ((folder.getDisplayName().equals("收件箱")||folder.getDisplayName().equals("Inbox")||
			  folder.getDisplayName().equals("已发送邮件")||folder.getDisplayName().equals("Sent Items"))&&
			  folder.getContentCount() > 0){    
			 depth++;                        
			 PSTMessage email = (PSTMessage)folder.getNextChild();   
			 while (email != null) {                         
				 printDepth();
				 System.out.println("Email: "+email.getSubject());   
				 System.out.println(email.getSenderEmailAddress()+"-"+email.getSenderName());
				 email = (PSTMessage)folder.getNextChild();
			 }                       
			 depth--;   
		  }             
		 depth--; 
			 
	 }
	 public void processEmail(PSTFolder folder) throws PSTException, java.io.IOException {
		 if (folder.hasSubfolders()) {        
			 Vector<PSTFolder> childFolders = folder.getSubFolders();   
			 for (PSTFolder childFolder : childFolders) {    
				 processEmail(childFolder);                     
			 }                
		 }                 
		 if ((folder.getDisplayName().equals("收件箱")||folder.getDisplayName().equals("Inbox")||
			  folder.getDisplayName().equals("已发送邮件")||folder.getDisplayName().equals("Sent Items"))&&
			  folder.getContentCount() > 0) {
			 System.out.println("@"+folder.getDisplayName());
			 PSTMessage email = (PSTMessage)folder.getNextChild();   
			 while (email != null) {                         
				 listEmail.add(email);
				 email = (PSTMessage)folder.getNextChild();
			 }                       
		  }             
	 }
	 public Map getEmailInfo(PSTMessage email,int currentMaxId,String virtualPath) throws PSTException, java.io.IOException{
		 Map map=new HashMap();
		 Map head=new HashMap();
		   String name=email.getSenderName()==null?"":email.getSenderName();
		   head.put("from", name+"<"+email.getSenderEmailAddress()+">");
		   head.put("to", email.getDisplayTo());
		   head.put("cc", email.getDisplayCC());
		   head.put("date", email.getClientSubmitTime());
		   head.put("subject", email.getSubject());
		   head.put("sender", email.getSenderEmailAddress());
		   head.put("message-id", email.getInternetMessageId());
		   head.put("delivered-to", "");
		   head.put("in-reply-to", email.getInReplyToId());
		 map.put("head", head);
		 map.put("originalHead", "");
		 map.put("content", email.getBodyHTML());
		 if(email.getNumberOfAttachments()>0){
			 int i=0;
			 int attachCount=0;
			 int current=0;
			 List attachments=new ArrayList();
			 while(i<email.getNumberOfAttachments()){
				 PSTAttachment attach=(PSTAttachment)email.getAttachment(i);
				 String fileName=attach.getLongFilename();
				 current=currentMaxId+attachCount;
				 writeLog("检测到附件: " +fileName,1);
			     try {
					saveFile(fileName,attach.getFileInputStream(),current);
					Map attachment = new HashMap();
					   attachment.put("id", current+"");
				       attachment.put("filename", virtualPath+"\\"+current+"_"+fileName);
				       attachment.put("attchname", fileName);
				       attachment.put("attchsize", attach.getFilesize()+" bytes");
				     
				       attachments.add(attachment);
				       
				       attachCount++;
				} catch (Exception e) {
					e.printStackTrace();
					writeLog("保存附件: " +fileName+"失败!",0);
				}
				i++;
				 
			 }
			 map.put("attachments", attachments);
		 }
		 return map;
	 }
	 private void saveFile(String fileName, InputStream in, int currentMaxId) throws Exception {
	      String osName = System.getProperty("os.name");
	      String storedir = getSaveAttachPath();
	      String separator = "";
	      if (osName == null) osName = "";
	      if (osName.toLowerCase().indexOf("win") != -1) {
	         separator = "\\";
	         if (storedir == null || storedir.equals("")) storedir = "c:\\tmp";
	      }
	      else {
	         separator = "/";
	         storedir = "/tmp";
	      }
	      File storefile = new File(storedir + separator + currentMaxId + "_" + fileName);
	      BufferedOutputStream bos = null;
	      BufferedInputStream bis = null;
	      try {
	         bos = new BufferedOutputStream(new FileOutputStream(storefile));
	         bis = new BufferedInputStream(in);
	         int c;
	         while ((c = bis.read()) != -1) {
	            bos.write(c);
	            bos.flush();
	         }

	      }
	      catch (Exception exception) {
	         exception.printStackTrace();
	         throw new Exception("文件保存失败!");
	      }
	      finally {
	         bos.close();
	         bis.close();
	      }

	   }
	 public void printDepth() {                
		 for (int x = 0; x < depth-1; x++) {           
			 System.out.print(" | ");                
		 }                
		 System.out.print(" |- ");        
	}
	    /**
	     * 记日志，包括log4j和显示在界面的日志信息
	     * 
	     * @param logInfo
	     * @param flag
	     *           0：错误信息，1：提示信息，2:正确信息
	     */

	  private void writeLog(final String logInfo, int flag) {
	       log.info(logInfo);

	 }
	 public static void main(String[] args) {
		 try {
//			 String filename="G:\\GL\\testPst\\gl_liuw(2).pst";
//			 String filename="G:\\GL\\testPst\\962523710.pst";
			 String filename="G:\\GL\\testPst\\outlook.ost";
			 ResolvePst pst=new ResolvePst();
			 PSTFile pstFile = new PSTFile(filename);           
			 System.out.println(pstFile.getMessageStore().getDisplayName());   
			 pst.processFolder(pstFile.getRootFolder());          
		  } catch (Exception err) {  
			  err.printStackTrace();        
		  } 
	}
}
